package org.shs.common.config;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.shs.user.model.UserModel;


/**
 * 
 * <br/>
 * <br/><b>Created:</b>&nbsp;&nbsp; Nov 5, 2008 4:34:01 PM
 *
 * @author anirvan
 *
 */
public class AccessFilter implements Filter 
{

    /**
     * Default constructor. 
     */
    public AccessFilter() 
    {}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() 
	{}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, 
	                     FilterChain chain) 
	throws IOException, ServletException 
	{
	   HttpServletRequest req = (HttpServletRequest)request;
      HttpSession session  = req.getSession();
      UserModel userBean = (UserModel)session.getAttribute("user");
      String uri = req.getRequestURI();
      
      uri = uri.substring(uri.lastIndexOf("/"), uri.length());
      // Let them see the log in page
      if("/".equals(uri) || uri.endsWith(".css") || uri.endsWith(".js")
               || uri.endsWith(".gif") || uri.endsWith(".jpg")
               || uri.endsWith(".png"))
      {
          chain.doFilter(request, response);
          return;
      }
      
      chain.doFilter(request, response);
      
      // Must be logged in to see anything else.
      if(null == userBean)
      {
          userBean = new UserModel();
          userBean.setMessage("You must log in first");
          userBean.setRequestedURL(constructFwdUrl(req));
          session.setAttribute("extLogin", userBean);
          request.getRequestDispatcher("/").forward(request, response);
          return;
      }
      else
      {
          chain.doFilter(request, response);
      }
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException 
	{}
	
	/**
	 * The reconstructed URL that the user needs to access.
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
   private String constructFwdUrl(HttpServletRequest req)
	{
	   StringBuffer sbUrl = null;
	   Enumeration paramNames = null;
	   String param = null;
	   
	   sbUrl = new StringBuffer(req.getRequestURL().toString() + "?");
	   paramNames = req.getParameterNames();
	   while (paramNames.hasMoreElements())
	   {
	      param = (String)paramNames.nextElement();
	      sbUrl.append(param + "=");
	      sbUrl.append(req.getParameter(param) + "&");
	   }
	   
	   return sbUrl.toString();
	}

}
